﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace Xtreme_Server.Plugins
{
    class PluginManager
    {
        WebServer ws;

        public PluginManager(ref WebServer srv)
        {
            ws = srv;
        }

        public void Load()
        {
            // rawr: http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx
            String[] pluginFiles = Directory.GetFiles(Program.PluginsDirectory, "*.dll");
            foreach (var plugin in pluginFiles)
            {
                Type objType = null;
                try
                {
                    //Assembly.GetExecutingAssembly().GetName().Name
                    //MessageBox.Show(Directory.GetCurrentDirectory());
                    Assembly asm = Assembly.Load(plugin);
                    if (asm != null)
                    {
                        objType = asm.GetType(asm.FullName);
                        if (objType != null)
                        {
                            if (typeof(IPlugin).IsAssignableFrom(objType))
                            {
                                //MessageBox.Show(Directory.GetCurrentDirectory());
                                IPlugin ipi = (IPlugin)Activator.CreateInstance(objType);
                                ipi.WebServer = this.ws;
                                //ipi.Host = Plugins.m_PluginsHost;
                                //ipi.Assembly = asm;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString(), "Xtreme Server encountered an error while loading the plugins.", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }
        }
    }
}
